import json
import time
import requests
from loguru import logger



class TornadoFather:

    def __init__(self) -> None:
        self._url= 'http://auks-security/tornado-cloud/SendTornadoMessage'
        self._header = {"Content-Type": "application/json;charset=UTF-8"}

        # self._url = 'http://10.12.14.120/security/SendMsgByTornado'
        # self._header = {"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}

    def send_content(self, content):
        """_summary_

        Args:
            content (_type_): 发送的内容

        Returns:
            _type_: 成功返回0000,失败返回None 
        """
        data = {
            "corp_id": "24338c6f0efd6c4bfb28f2ccbf9df6a4",
            "api_key": "a220205a-49cd-4a7c-930a-f30a8bb55bd7",
            "policyName": "AUKS_ML6KA0_00021",
            "userId": "K2207368",
            "desc":content
        }
        # data = {
        #     "userID": "K2207368",
        #     "jobCat": "agv_battery",
        #     "scene": "ra_lab",
        #     "tag": "battery",
        #     "desc": content,
        #     "param": ""
        # }
        # # logger.debug("send request")
        # return
        try:
            response = requests.post(self._url, data=json.dumps(data) , headers=self._header)
            res = eval(response.text)
            # print(response.text)
            # print(response.text)
            # print(response)
            # print(type(response.text))
            # print(eval(response.text).get("errcode"))
            # print(res.get("errcode"))
            # print(res.get("errcode")=="0000")
            if res.get("errcode") != "0000":
                err_msg = res.get("errmsg") 
                logger.warning(f"龙卷风发送失败-->{err_msg}")
                return err_msg 
        except Exception as e:
            logger.error(e)



class Tornado(TornadoFather):
    

    def __init__(self,name,count,interval):
        """_summary_

        Args:
            name (_type_): 龙卷风的名字
            count (_type_): 一个小时内限制的次数
            interval (_type_): 发送的间隔
        """
        super(Tornado,self).__init__()
        # 初始化上次调用函数的时间为0
        self.last_called = 0
        # 用来统计龙卷风发送的次数
        self.name = name
        self.count = count
        self.interval = interval
        self.data = {} 


    def send(self,content):
        """_summary_
        Args:
            content (_type_): 发送的内容
            interval (_type_): 间隔的时间,以秒为单位
        """
        current_time = time.time()
        # 检查是否已经过了阈值(要求阈值小于1小时)
        if current_time - self.last_called >= self.interval:
            # 统计某个龙卷风在一段时间内发送的次数 
            if self.data.get(self.name) is None:
                self.data.update({self.name:0,"start_time":time.time(),"end_time":time.time(),"send_flag":True})
            else:
                self.data.update({self.name:self.data.get(self.name) + 1,"end_time":time.time()})

            self.check_limit_by_time()
            # 如果发送龙卷风的标志位为False,则不再进行龙卷风发送
            if not self.data.get("send_flag"):
                return
            # 发送龙卷风
            self.send_content(content)
            # 更新上次调用函数的时间
            self.last_called = current_time
        else:
            pass


    def check_limit_by_time(self):
        """限制一段时间内发送的次数
        """
        start_time = self.data.get("start_time")
        end_time = self.data.get("end_time")
        counter = self.data.get(self.name)
        if end_time - start_time < 1 * 60 * 60 :# 如果一个小时内龙卷风发送了超过了3笔,那么这个龙卷风就不再进行发送
            if  counter >= self.count:
                self.data.update({"send_flag":False})
                # logger.warning("一个小时超3过笔,暂停发送");
            else:
                pass
                # logger.warning("一个小时不超超过5笔");
        elif end_time - start_time >= 2 * 60 * 60:# 两个小时后在重新发送龙卷风,同时start_time设置为当前时间
            self.data.update({"send_flag":True,"start_time":time.time(),self.name:0})
            # logger.warning("2后小时龙卷风恢复发送");





if __name__ == "__main__":
    #10分钟一次,但是如果一个小时内超过3笔,则暂停     剩余的时间 + 一个小时   
    batteryTornado = Tornado("battery", 3 , 10 * 60)
    # i = 0
    # while True:
    #     i = i + 1
    #     batteryTornado.send(f"test{i}")
    batteryTornado.send(f"test")

